import React, { Component } from "react";
import { withRouter } from "react-router-dom";
import { message, Modal } from "antd";
import "./index.less";
import memoryUtil from "../../utils/memoryUtil";
import storageUtil from "../../utils/storageUtil";
import { formateData } from "../../utils/dataUtil";
import { reqWeather } from "../../api/index";
import menuList from "../../config/menuConfig";
import LinkButton from "../linkButton";
const { confirm } = Modal;

class Header extends Component {
  state = {
    currentTime: formateData(Date.now()),
    weatherPictureUrl: "",
    weatherText: "",
    titleText: "",
  };

  getTime = () => {
    setInterval(() => {
      const currentTime = formateData(Date.now());
      this.setState({ currentTime });
    }, 1000);
  };

  getWeather = async () => {
    let data = await reqWeather("深圳");
    let err = data.msg;
    if (err) {
      message.error(err);
      return;
    }
    data = data.result;
    let { weather_curr: weatherText, weather_icon: weatherPictureUrl } = data;
    this.setState({ weatherText, weatherPictureUrl });
  };

  getTitle = (location) => {
    let pathname = location.pathname;
    let titleText = "";
    menuList.forEach((item) => {
      if (item.key === pathname) {
        titleText = item.title;
      } else if (item.children) {
        let cItem = item.children.find((cItem) => cItem.key === pathname);
        if (cItem) {
          titleText = cItem.title;
        }
      }
    });
    this.setState({ titleText });
  };

  getTitleAndListen = () => {
    let location = this.props.location;
    this.getTitle(location);
    this.props.history.listen((location) => {
      this.getTitle(location);
    });
  };

  logout = () => {
    confirm({
      title: "确定退出登陆吗?",
      okText: "确认",
      cancelText: "取消",
      onOk: () => {
        storageUtil.removeUser();
        memoryUtil.user = {};
        this.props.history.replace("/login");
      },
    });
  };

  constructor(props) {
    super(props);
    this.getWeather();
  }

  componentDidMount() {
    this.getTime();
    this.getTitleAndListen();
  }

  render() {
    let { username } = memoryUtil.user;
    let { currentTime, weatherPictureUrl, weatherText, titleText } = this.state;
    if (!weatherPictureUrl) {
      weatherPictureUrl =
        "http://api.map.baidu.com/images/weather/day/qing.png";
      weatherText = "晴";
    }
    return (
      <div className="header">
        <div className="header-top">
          <span>欢迎, {username}</span>
          <LinkButton onClick={this.logout}>退出</LinkButton>
        </div>
        <div className="header-bottom">
          <div className="header-bottom-left">{titleText}</div>
          <div className="header-bottom-right">
            <span>{currentTime}</span>
            <img src={weatherPictureUrl} alt="weather" />
            <span>{weatherText}</span>
          </div>
        </div>
      </div>
    );
  }
}
export default withRouter(Header);
